package logging

import (
	"fmt"
	"github.com/EDDYCJY/go-gin-app/pkg/file"
	"github.com/EDDYCJY/go-gin-app/pkg/setting"
	"os"
	"time"
)

func getLogFilePath() string {
	return fmt.Sprintf("%s%s", setting.AppSetting.RuntimeRootPath,setting.AppSetting.LogSavePath)
}

func getLogFileName() string {
	return fmt.Sprintf("%s_%s.%s", setting.AppSetting.LogSaveName,time.Now().Format(setting.AppSetting.TimeFormat), setting.AppSetting.LogFileExt)
}

func openLogFile(fileName string, filePath string) (*os.File, error) {
	dir, err := os.Getwd()
	if err != nil {
		return nil, fmt.Errorf("os.Getwd err: %v", err)
	}
	src := dir + "/" + filePath
	perm := file.CheckPermission(src)
	if perm == true {
		//没权限
		return nil, fmt.Errorf("file.CheckPermission Permission denied src: %s", src)
	}
	err = file.IsNotExistMkDir(src)
	if err != nil {
		return nil, fmt.Errorf("file.IsNotExistMkDir src: %s err :%s", src, err)
	}
	f,err := file.Open(src+fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return nil, fmt.Errorf("Fail to OpenFile :%v", err)
	}
	return f,err
}
//func getLogFileFullPath() string {
//	prefixPath := getLogFilePath()
//	suffixPath := fmt.Sprintf("%s_%s.%s", setting.AppSetting.LogSavePath,time.Now().Format(setting.AppSetting.TimeFormat), setting.AppSetting.LogFileExt)
//	return fmt.Sprintf("%s%s", prefixPath, suffixPath)
//}
//
//func openLogFile(path string) *os.File{
//	_,err := os.Stat(path)
//	switch {
//		case os.IsNotExist(err):
//			mkDir()
//		case os.IsPermission(err):
//			log.Fatalf("没权限：%v", err)
//	}
//	handle,err := os.OpenFile(path, os.O_APPEND | os.O_CREATE | os.O_RDONLY, 0644)
//	if err != nil {
//		log.Fatalf("fail to open :%v", err)
//	}
//	return handle
//}
//
///**
//生成文件夹
// */
//func mkDir() {
//	dir,_ := os.Getwd()
//	err := os.MkdirAll(dir+"/"+getLogFilePath(),os.ModePerm)
//	if err !=nil {
//		panic(err)
//	}
//}